package lyx.totalexample.imagesearch.util;

import lombok.RequiredArgsConstructor;
import lyx.totalexample.imagesearch.entity.ImageSave;
import lyx.totalexample.imagesearch.mapper.ImageSaveMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Component
@RequiredArgsConstructor
public class imageInitUtil {

    @Value("${upload.path}")
    private String uploadPath;

    private final ImageSaveMapper imageSaveMapper;

    /**
     * 初始化照片存入数据库
     */
    public void init() {
        // 初始化照片存入数据库
        File file = new File(uploadPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        File[] files = file.listFiles();
        List<ImageSave> imageSaves = new ArrayList<>();
        if (files != null) {
            for (File f : files) {
                if (f.isFile()) {
                    ImageSave  imageSave = new ImageSave();
                    imageSave.setImageName(f.getName());
                    imageSave.setImageUrl(f.getAbsolutePath());
                    imageSaves.add(imageSave);
                    System.out.println(f.getAbsolutePath());
                }
            }
        }
        imageSaveMapper.insert(imageSaves);
    }

    /**
     * 上传文件
     * @param file 上传的文件
     * @return 可访问的文件路径
     * @throws IOException IO异常
     */
    public String uploadFile(MultipartFile file) throws IOException {
        // 1. 检查文件是否为空
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }

        // 2. 创建日期目录，防止文件过多
/*        String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
        File saveDir = new File(uploadPath + dateDir);
        if (!saveDir.exists()) {
            saveDir.mkdirs();
        }*/
        File saveDir = new File(uploadPath);
        // 3. 生成唯一文件名s
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + suffix;

        // 4. 保存文件
        File dest = new File(saveDir, newFileName);
        file.transferTo(dest);

        // 5. 返回可访问的文件路径
        return  uploadPath + "/" + newFileName;
    }
}
